<?php

/**
 *  PHP 邮件发送类
 * 
 * @author 叶风
 * Qq:    355007778
 * Email: ye.fn@163.com
 *	 
 */
set_time_limit(300);
class mail
{
	var $attachmentData = '';
	var $boundary = 'y############yhzwgf############f';
    
    /**
     * server, user, password
     * @var array 
     */
	var $config = array();
    
	function __construct()
	{
        
	 	$this->config = require CONFIG_DIR .'mail.php';
		$this->coding = YF_f::$config['charset']; 
        $this->db = YF_f::get_db_link();
	}
    
	/**
     * 发送成功返回0
     * 
     * @param array $to 地址
     * @param string $title  标题
     * @param string $content  内容
     * @param array $cc  抄送
     * @return string|0
     */
	function send($to, $title, $content, $cc=array() )
	{
		is_array($to) or $to = array($to);
		$toA =  array_merge($to, $cc);
		$c = $this->config;
        if(!$c['server'] or !$c['user'])
			return 'server config error';
		
        //开始SMTP会话
		list($host, $prot) = explode(':',$c['server']);
		$prot or $prot=25;
		$this->sock = fsockopen($host, $prot, $errno, $errstr, 15);
        if (!$this->sock){
            YF_f::error("$errno $errstr");
            return "errno: $errno";
         }
		fgets($this->sock);
        
		$this->request('HELO '. $_SERVER["SERVER_NAME"]);
		$this->request('AUTH LOGIN '.base64_encode($c['user']));
		$m = $this->request(base64_encode($c['password']));
        if (strpos($m, '235')!==0)
            return $m;
        
		$this->request("MAIL FROM:<{$c[user]}>");
		foreach($toA as $t)
			$this->request("RCPT TO:<$t>");
		$this->request('DATA');
		$s = "Date:".date("r")."
From:{$c[cname]}<{$c[user]}>
To:".implode(',', $to)."
Cc:".implode(',', $cc)."
Subject:=?{$this->coding}?B?". base64_encode($title)."?=
Message-ID: <".time().rand(0,999).">
Mime-Version: 1.0
Content-Type: multipart/mixed; boundary=\"{$this->boundary}\"

This is a multi-part message in MIME format.

--{$this->boundary}
Content-Type: text/html; charset=\"{$this->coding}\"
Content-Transfer-Encoding: 7bit

{$content} <br /><br /><br />". $c['signature']. "
";
		
		fputs($this->sock,$s.$this->attachmentData."--{$this->boundary}--\r\n\r\n");
		$m = $this->request(".");
		$this->request("QUIT");
		fclose($this->sock);
		if (strpos($m, '250' )===0)
		 {
		 	$this->db->save('mail_box',array('to_name'=>implode(';', $toA), 'title'=>$title, 'content'=>$content));
		 	return 0;
		 }
		return 'Send mail failed.';
	}
    protected function request($q)
	{
		fputs($this->sock,$q."\r\n");
		$m = fgets($this->sock);
		if (YF_f::$config['debug']>2)
			YF_f::$arr['debug_info'][] = $q.' >> '.$m;
		return $m;
	}

    /**
     * 增加附件
     *   图片引用 cid:
     * @param type $file
     * @param type $name
     * @return type 附件的ID
     */
	function addAttachment($file, $name)
	{
		$fileData = chunk_split(base64_encode(file_get_contents($file)));
		$fileName = base64_encode($name?$name:basename($file));
		$fileID =  sprintf("%09d", crc32($file));
		$this->attachmentData .= "
--{$this->boundary}
Content-Type: application/octet-stream; name=\"=?{$this->coding}?B?{$fileName}?=\"
Content-Transfer-Encoding: base64\r\nContent-ID: <{$fileID}>
Content-Disposition: attachment; filename=\"=?{$this->coding}?B?{$fileName}?=\"

{$fileData}

";
		return $fileID;
	}
    

	function test()
	{
		$s = $this->send($this->config['user'], 'test', 'Test'. date('Ymd His') );
		ajax_json(lang::g($s===TRUE ? 'OK' :$s));
	}
}

?>
